/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package eypweb_bsc;

import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;

/**
 *
 * @author Kohalmi Istvan
 */

// tranzakcio tipusok kezeleseert felelos kepernyot megvalosito osztaly
public class TransactionRegistry implements Initializable {

    @FXML
    private Button btnNew;
    @FXML
    private Button btnMod;
    @FXML
    private Button btnCan;
    @FXML
    private Button btnRes;
    @FXML
    private Button btnCom;
    @FXML
    private Button btnEsc;
    @FXML
    private Button btnSkin;
    @FXML
    private Label errorLabel;
    @FXML
    private TextField tfName;
    @FXML
    private ChoiceBox cbDelta;
    @FXML
    private ChoiceBox cbDecrease;
    @FXML
    private ChoiceBox cbInterest;
    @FXML
    private ChoiceBox cbDividend;
    @FXML
    private ChoiceBox cbMarket;
    @FXML
    private ChoiceBox cbCurrency;
    @FXML
    private ChoiceBox cbStyle;
    @FXML
    private TextField tfStart;
    @FXML
    private TextField tfEnd;
    @FXML
    private TableView<Transaction> masterData;

    public TransactionRegistry() {
        super();
    }

    @FXML
    private void handleNewButtonAction(ActionEvent event) {
        if (btnNew.getText().equals("Új elem")) {
            btnMod.setDisable(true);
            btnCom.setDisable(true);
            btnRes.setDisable(true);
            btnCan.setDisable(false);
            btnNew.setText("Rendben");
            tfName.clear();
            cbDelta.getSelectionModel().select("nem");
            cbDecrease.getSelectionModel().select("nem");
            cbInterest.getSelectionModel().select("nem");
            cbDividend.getSelectionModel().select("nem");
            cbMarket.getSelectionModel().select("nem");
            cbCurrency.getSelectionModel().select("nem");
            tfStart.clear();
            tfEnd.clear();
        } else {
            if (tfName.getText().isEmpty()) {
                errorLabel.setText("A mezőket kötelező kitölteni!");
                return;
            }
            try {
                Date start = Date.valueOf(tfStart.getText());
                Date end = Date.valueOf(tfEnd.getText());
                if (start.after(end)) {
                    errorLabel.setText("A kezdődátum nem lehet későbbi, mint a végdátum!");
                    return;
                }
            } catch (Exception e) {
                errorLabel.setText("A dátum nincs megfelelően formázva!");
                return;
            }
            Transaction transaction = new Transaction();
            transaction.setId(0);
            transaction.setName(tfName.getText());
            transaction.setDeltaVolume(cbDelta.getSelectionModel().getSelectedItem().toString());
            transaction.setDecrAV(cbDecrease.getSelectionModel().getSelectedItem().toString());
            transaction.setSepInterest(cbInterest.getSelectionModel().getSelectedItem().toString());
            transaction.setSepDividend(cbDividend.getSelectionModel().getSelectedItem().toString());
            transaction.setMktRateGain(cbMarket.getSelectionModel().getSelectedItem().toString());
            transaction.setCurRateGain(cbCurrency.getSelectionModel().getSelectedItem().toString());
            transaction.setStartDate(tfStart.getText());
            transaction.setEndDate(tfEnd.getText());
            transaction.setModified();
            masterData.getItems().add(transaction);
            btnMod.setDisable(false);
            btnRes.setDisable(false);
            btnCom.setDisable(false);
            btnNew.setText("Új elem");
        }
    }

    @FXML
    private void handleModifyButtonAction(ActionEvent event) {
        if (btnMod.getText().equals("Módosít")) {
            Transaction selectedItem = masterData.getSelectionModel().getSelectedItem();
            if (selectedItem != null) {
                tfName.setText(selectedItem.getName());
                cbDelta.getSelectionModel().select(selectedItem.getDeltaVolume());
                cbDecrease.getSelectionModel().select(selectedItem.getDecrAV());
                cbInterest.getSelectionModel().select(selectedItem.getSepInterest());
                cbDividend.getSelectionModel().select(selectedItem.getSepDividend());
                cbMarket.getSelectionModel().select(selectedItem.getMktRateGain());
                cbCurrency.getSelectionModel().select(selectedItem.getCurRateGain());
                tfStart.setText(selectedItem.getStartDate());
                tfEnd.setText(selectedItem.getEndDate());
                btnMod.setText("Rendben");
                btnNew.setDisable(true);
                btnCom.setDisable(true);
                btnRes.setDisable(true);
                btnCan.setDisable(false);
            }
        } else {
            if (tfName.getText().isEmpty()) {
                errorLabel.setText("A mezőket kötelező kitölteni!");
                return;
            }
            try {
                Date start = Date.valueOf(tfStart.getText());
                Date end = Date.valueOf(tfEnd.getText());
                if (start.after(end)) {
                    errorLabel.setText("A kezdődátum nem lehet későbbi, mint a végdátum!");
                    return;
                }
            } catch (Exception e) {
                errorLabel.setText("A dátum nincs megfelelően formázva!");
                return;
            }
            Transaction selectedItem = masterData.getSelectionModel().getSelectedItem();
            if (selectedItem != null) {
                selectedItem.setName(tfName.getText());
                selectedItem.setDeltaVolume(cbDelta.getSelectionModel().getSelectedItem().toString());
                selectedItem.setDecrAV(cbDecrease.getSelectionModel().getSelectedItem().toString());
                selectedItem.setSepInterest(cbInterest.getSelectionModel().getSelectedItem().toString());
                selectedItem.setSepDividend(cbDividend.getSelectionModel().getSelectedItem().toString());
                selectedItem.setMktRateGain(cbMarket.getSelectionModel().getSelectedItem().toString());
                selectedItem.setCurRateGain(cbCurrency.getSelectionModel().getSelectedItem().toString());
                selectedItem.setStartDate(tfStart.getText());
                selectedItem.setEndDate(tfEnd.getText());
                selectedItem.setModified();
                btnMod.setText("Módosít");
                btnNew.setDisable(false);
                btnCom.setDisable(false);
                btnRes.setDisable(false);
            }
        }
    }

    @FXML
    private void handleCancelButtonAction(ActionEvent event) {
        btnNew.setDisable(false);
        btnMod.setDisable(false);
        btnRes.setDisable(false);
        btnCom.setDisable(false);
        btnNew.setText("Új elem");
        btnMod.setText("Módosít");
        btnCan.setDisable(true);
    }

    @FXML
    private void handleResetButtonAction(ActionEvent event) {
        Director director = Director.getInstance();
        AccessInfo ai = director.getAccessInfo();
        ObservableList<Transaction> transactions = FXCollections.observableArrayList();
        try {
            Connection con = DriverManager.getConnection("jdbc:sqlserver://" + ai.getIPAddress() + ":" + ai.getPort() + ";databaseName=" + ai.getDBName(), ai.getUser(), ai.getPass());
            String TransactionQuery = "SELECT * FROM tranzakcio";
            PreparedStatement stmt = con.prepareStatement(TransactionQuery);
            ResultSet results = stmt.executeQuery();
            while (results.next()) {
                Transaction transaction = new Transaction();
                transaction.setId(results.getInt(1));
                transaction.setName(results.getNString(2));
                if (results.getBoolean(3))
                    transaction.setDeltaVolume("igen");
                else
                    transaction.setDeltaVolume("nem");
                if (results.getBoolean(4))
                    transaction.setDecrAV("igen");
                else
                    transaction.setDecrAV("nem");
                if (results.getBoolean(5))
                    transaction.setSepInterest("igen");
                else
                    transaction.setSepInterest("nem");
                if (results.getBoolean(6))
                    transaction.setSepDividend("igen");
                else
                    transaction.setSepDividend("nem");
                if (results.getBoolean(7))
                    transaction.setMktRateGain("igen");
                else
                    transaction.setMktRateGain("nem");
                if (results.getBoolean(8))
                    transaction.setCurRateGain("igen");
                else
                    transaction.setCurRateGain("nem");
                transaction.setStartDate(results.getDate(9).toString());
                transaction.setEndDate(results.getDate(10).toString());
                transactions.add(transaction);
            }
            con.close();
        } catch (SQLException sqle) {
            errorLabel.setText(sqle.getMessage());
        }
        masterData.getItems().clear();
        masterData.getItems().addAll(transactions);
    }

    @FXML
    private void handleCommitButtonAction(ActionEvent event) {
        Director director = Director.getInstance();
        AccessInfo ai = director.getAccessInfo();
        ObservableList<Transaction> transactions = masterData.getItems();
        try {
            Connection con = DriverManager.getConnection("jdbc:sqlserver://" + ai.getIPAddress() + ":" + ai.getPort() + ";databaseName=" + ai.getDBName(), ai.getUser(), ai.getPass());
            String insertAction = "exec AddOrModifyTransaction ?,?,?,?,?,?,?,?,?,?";
            for (Transaction tran : transactions) {
                if (tran.getModified()){
                    PreparedStatement insertStmt = con.prepareStatement(insertAction);
                    insertStmt.setInt(1, tran.getId());
                    insertStmt.setNString(2, tran.getName());
                    insertStmt.setBoolean(3, tran.getDeltaVolume().equals("igen"));
                    insertStmt.setBoolean(4, tran.getDecrAV().equals("igen"));
                    insertStmt.setBoolean(5, tran.getSepInterest().equals("igen"));
                    insertStmt.setBoolean(6, tran.getSepDividend().equals("igen"));
                    insertStmt.setBoolean(7, tran.getMktRateGain().equals("igen"));
                    insertStmt.setBoolean(8, tran.getCurRateGain().equals("igen"));
                    insertStmt.setDate(9, Date.valueOf(tran.getStartDate()));
                    insertStmt.setDate(10, Date.valueOf(tran.getEndDate()));
                    insertStmt.execute();
                }
            }
            con.close();
        } catch (SQLException sqle) {
            errorLabel.setText(sqle.getMessage());
        }
    }

    @FXML
    private void handleEscapeButtonAction(ActionEvent event) {
        Director director = Director.getInstance();
        director.initializeMainMenu();
    }

    @FXML
    private void handleCSVButtonAction(ActionEvent event) {
        CSVHandler.exportTransaction(masterData.getItems());
    }

    @FXML
    private void handleXLSButtonAction(ActionEvent event) {
        XLSHandler.exportTransaction(masterData.getItems());
    }

    @FXML
    private void handleXMLButtonAction(ActionEvent event) {
        XMLHandler.exportTransaction(masterData.getItems());
    }
    
    @FXML
    private void handleRowSelect(MouseEvent event) {
        if (masterData.getSelectionModel().getSelectedItem() != null) {
            btnMod.setDisable(false);
        } else {
            btnMod.setDisable(true);
        }
    }
    
    private void handleSkinButtonAction(ActionEvent event){
        Director director = Director.getInstance();
        director.reskin(cbStyle.getSelectionModel().getSelectedItem().toString());
    }

    public void initialize(URL url, ResourceBundle bundle) {
        handleResetButtonAction(new ActionEvent());
        
        cbDelta.getItems().addAll("igen","nem");
        cbDecrease.getItems().addAll("igen","nem");
        cbInterest.getItems().addAll("igen","nem");
        cbDividend.getItems().addAll("igen","nem");
        cbMarket.getItems().addAll("igen","nem");
        cbCurrency.getItems().addAll("igen","nem");
        
        cbDelta.getSelectionModel().select("nem");
        cbDecrease.getSelectionModel().select("nem");
        cbInterest.getSelectionModel().select("nem");
        cbDividend.getSelectionModel().select("nem");
        cbMarket.getSelectionModel().select("nem");
        cbCurrency.getSelectionModel().select("nem");
        
        TableColumn<Transaction, String> nameCol = new TableColumn<Transaction, String>("Megnevezés");
        nameCol.setCellValueFactory(new PropertyValueFactory("name"));

        TableColumn<Transaction, String> deltaCol = new TableColumn<Transaction, String>("Darabszám v.");
        deltaCol.setCellValueFactory(new PropertyValueFactory("deltaVolume"));

        TableColumn<Transaction, String> decreaseCol = new TableColumn<Transaction, String>("BSZÉ csökken");
        decreaseCol.setCellValueFactory(new PropertyValueFactory("decrAV"));
        
        TableColumn<Transaction, String> interestCol = new TableColumn<Transaction, String>("Elh. kamat");
        interestCol.setCellValueFactory(new PropertyValueFactory("sepInterest"));
             
        TableColumn<Transaction, String> dividendCol = new TableColumn<Transaction, String>("Elh. osztalék");
        dividendCol.setCellValueFactory(new PropertyValueFactory("sepDividend"));
        
        TableColumn<Transaction, String> marketCol = new TableColumn<Transaction, String>("Piaci árf. nyereség");
        marketCol.setCellValueFactory(new PropertyValueFactory("mktRateGain"));
        
        TableColumn<Transaction, String> currencyCol = new TableColumn<Transaction, String>("Deviza árf. nyereség");
        currencyCol.setCellValueFactory(new PropertyValueFactory("curRateGain"));
        
        TableColumn<Transaction, String> startCol = new TableColumn<Transaction, String>("Hatály kezdete");
        startCol.setCellValueFactory(new PropertyValueFactory("startDate"));

        TableColumn<Transaction, String> endCol = new TableColumn<Transaction, String>("Hatály vége");
        endCol.setCellValueFactory(new PropertyValueFactory("endDate"));
        
        masterData.getColumns().setAll(nameCol, deltaCol, decreaseCol, interestCol, dividendCol, marketCol, currencyCol, startCol, endCol);
    }
}